package cn.dujc.superkid.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.dujc.core.adapter.BaseQuickAdapter;
import cn.dujc.core.ui.BaseFragment;
import cn.dujc.core.ui.BaseListFragment;
import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.activities.ContinueActivity;
import cn.dujc.superkid.activities.GoodQueActivity;
import cn.dujc.superkid.activities.ResolvtionActivity;
import cn.dujc.superkid.adapter.RecyclerViewAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.ChannelEntity;
import cn.dujc.superkid.bean.CourseEntity;
import cn.dujc.superkid.bean.CourseResult;
import cn.dujc.superkid.bean.GoodQuestionResult;
import cn.dujc.superkid.bean.QuestionResultsResult;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.SubjectEntity;
import cn.dujc.superkid.configs.Globals;
import cn.dujc.superkid.utils.Preferences;

import static cn.dujc.superkid.R.id.good_que_title;

public class GoodFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    private final List<SubjectEntity> mList = new ArrayList<>();
    private RecyclerViewAdapter mAdapter;
    private String categoryId;
    private int mPage = 0;
    private TextView goodTitle;
    private int titleId;

    @Override
    public int getViewId() {
        return R.layout.fragment_list;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        loadData();
        initClick();
    }
   RecyclerView recyclerView;
    private void initViews() {
        recyclerView= (RecyclerView) findViewById(R.id.test_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter=new RecyclerViewAdapter(null);
        mAdapter.setOnLoadMoreListener(this,recyclerView);
        recyclerView.setAdapter(mAdapter);
    }

    private void initClick() {
        mAdapter.addOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.good_continu:
                        Intent intent = new Intent(getActivity(), ContinueActivity.class);
                        intent.putExtra("type", mList.get(position).getQuestion_type());
                        intent.putExtra("title", mList.get(position).getQuestion_title());
                        intent.putExtra("good_key", mList.get(position).getGood_key());
                        List<String> answers = mList.get(position).getExercises_answer();
                        intent.putStringArrayListExtra("answer", (ArrayList<String>) answers);
                        startActivity(intent);
                        break;
                    case R.id.good_resolvtion:
                        Intent intent1 =new Intent(getActivity(), ResolvtionActivity.class);
                        intent1.putExtra("title",mList.get(position).getQuestion_title());
                        intent1.putExtra("jiexi",mList.get(position).getExplain_ex());
                        intent1.putExtra("daan",mList.get(position).getCorrect_answer().get(0));
                        startActivity(intent1);
                        break;
                }
            }
        });
        mAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                delete(position);
                return false;
            }
        });
    }

    private void delete(final int pos) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示").setMessage("确认删除这条记录吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
                QMap map=QMap.build()
                        .put("good_question_id",mAdapter.getData().get(pos).getId())
                        .put("user_id", Integer.parseInt(loginResult.getUid()))
                        .put("channel", Preferences.getInstance().getChannel(mActivity).getChannel_id())
                        .put("logincode", loginResult.getLogincode()).create();
                Log.e("qqmap",map.toString());
                HttpHelper.getUserCenter().memberDelGoodQuestion(map).enqueue(new ResultCallBack<Result<Object>>(mActivity) {
                    @Override
                    public void onSuccessCallback(int code, Result<Object> body) {
                        ToastUtil.showToast(mActivity,body.getMsg());
                        mAdapter.removeData(pos);
                    }
                });
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ToastUtil.showToast(getContext(), "取消操作");
            }
        });
        builder.show();
    }



    private void loadData() {
        final QMap.Builder map = QMap.build();
        Bundle bundle = getArguments();
        categoryId = bundle.getString("str");
        if (categoryId != null) {
            map.put("category_id", categoryId);
        }
        final ChannelEntity channel = Preferences.getInstance().getChannel(mActivity);
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(mActivity);
        if (channel != null) map.put("channel", channel.getChannel_id());
        map.put("user_id", loginResult.getUid());
        map.put("logincode", loginResult.getLogincode());
        map.put("num", 10);
        map.put("page", mPage);

        HttpHelper.getUserCenter().memberGoodQuestion(map.create()).enqueue(new ResultCallBack<Result<GoodQuestionResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<GoodQuestionResult> body) {
                mList.addAll(body.getData().getList());
                if (mPage == 0) {
                    mAdapter.setNewData(body.getData().getList());
                    if (mAdapter.getItemCount() == 0) {
                        TextView tv = new TextView(mActivity);
                        tv.setText("暂无数据");
                        tv.setTextSize(14);
                        tv.setTextColor(Color.parseColor("#222222"));
                        mAdapter.setEmptyView(tv);
                    }
                } else {
                    mAdapter.addData(body.getData().getList());
                    mAdapter.loadMoreComplete();
                }
                if (mAdapter.getItemCount() < 20) {
                    mAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onFailureCallback(int code, String msg) {
//                super.onFailureCallback(code, msg);
                TextView tv = new TextView(mActivity);
                tv.setText("暂无数据");
                tv.setTextSize(14);
                tv.setTextColor(Color.parseColor("#222222"));
                mAdapter.setEmptyView(R.layout.layout_empty);
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        mPage++;
        loadData();
    }
}
